<?php

namespace App\Http\Middleware;

use App\Exceptions\TokenNotExists;
use App\Services\TokenValidator;
use Closure;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\SignatureInvalidException;
use Illuminate\Contracts\Auth\Factory as Auth;

class CheckUser
{
    /**
     * The authentication guard factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    private static $key = 'xzg_zhs';

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {

        (new TokenValidator())->goCheck($request);

        try{
            $token = $request->bearerToken();
            if(!($user_id = JWT::decode($token,self::$key,['HS256'])->user_id)){
                throw new TokenNotExists('Unauthorized',401);
            }

            $request->attributes->set('user_id',$user_id);
        }catch (SignatureInvalidException $e){
            throw new TokenNotExists($e->getMessage(),401);
        }catch (ExpiredException $e){
            throw new TokenNotExists($e->getMessage(),401);
        }catch (\Exception $e){
            throw new TokenNotExists($e->getMessage(),401);
        }

        return $next($request);
    }
}
